import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:expandable/expandable.dart';
import 'package:shop/shop/merchant/Index.dart';
import 'package:shop/shop/merchant/MyOrderList.dart';
import 'package:url_launcher/url_launcher.dart';
class XianYouYuyue extends StatefulWidget {
  XianYouYuyue({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _XianYouYuyue createState() => _XianYouYuyue();
}

class _XianYouYuyue extends State<XianYouYuyue> {

  bool isShow=true;
  SharedPreferences prefs;
  String merchantID=""; //商户ID
  List xianyouYuyue=[]; //现有预约集合
  String mType='';     //店铺类型
  int page = 1;        //页数

  // 上拉加载控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  void _onRefresh() async{
    _refreshController.refreshCompleted();
  }

  //初始化数据
  @override
  void initState() {
    super.initState();
    _onLoading();
  }

  // 加载商户已完成的订单
  _onLoading() async{
    prefs = await SharedPreferences.getInstance();
    merchantID = prefs.getString("merchantID");
    var x = await HttpUtil().get("/waimai/merchantYuyue/getXianYouandGuoQiYuyue?limit=10&page=${page}&merchantId="+merchantID+"&type=0");
    page++;
    if(x['code']==200){
      xianyouYuyue.addAll(x['data']);
      if(x['data'].length<1){
        _refreshController.loadNoData();
        return;
      }
    }
    if(mounted){
      setState(() {});
      _refreshController.loadComplete();
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      // body: ListView(
      //   children: [
      //     _getOrders(),
      //   ],
      // )
      body: Column(
        children: [
          Expanded(child: SmartRefresher(
            enablePullDown: false,
            enablePullUp: true,
            header: WaterDropHeader(),
            footer: CustomFooter(
              builder: (BuildContext context,LoadStatus mode){
                Widget body ;
                if(mode==LoadStatus.idle){
                  body =  Text("上拉加载");
                }
                else if(mode==LoadStatus.loading){
                  body =  CupertinoActivityIndicator();
                }
                else if(mode == LoadStatus.failed){
                  body = Text("加载失败！点击重试！");
                }
                else if(mode == LoadStatus.canLoading){
                  body = Text("松手,加载更多!");
                }
                else{
                  body = Text("没有更多数据了!");
                }
                return Container(
                  height: 55.0,
                  child: Center(child:body),
                );
              },
            ),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
              itemBuilder: (c, i) => Card(child: _shouYuyue(xianyouYuyue[i])),
              itemExtent: 100.0,
              itemCount: xianyouYuyue.length,
            ),
          ),)
        ],
      ),
    );
  }

  GestureDetector _shouYuyue(item){
    return GestureDetector(
      child: Container(
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(item['nick'],style: TextStyle(fontWeight: FontWeight.bold,fontSize: 20,color: Colors.red),),
                Text("预留电话:"+item['phone'])
              ],
            ),
            SizedBox(height: 10,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(item['mgoods']['gname']),
                Text(item['yuyueTime'],style: TextStyle(color: Colors.black12),)
              ],
            ),
            Row(
              children: [
                Text("人数："+item['num'].toString())
              ],
            )
          ],
        ),
      ),
      onTap: (){

      },
    );
  }

  //得订单
  // _getOrders(){
  //   List<Widget> x = [];
  //   for(int i=0;i<orderList.length;i++){
  //     x.add(
  //         ExpandableNotifier(
  //             child: Padding(
  //               padding: const EdgeInsets.all(0),
  //               child: Card(
  //                 clipBehavior: Clip.antiAlias,
  //                 child: Column(
  //                   children: <Widget>[
  //                     SizedBox(
  //                       // height: 150,
  //                       child: Container(
  //                         child: Column(
  //                           children: [
  //                             Row(
  //                               mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //                               children: [
  //                                 Text(orderList[i]['address']['adName']),
  //                                 GestureDetector(child: Icon(Icons.phone),onTap: () async {
  //                                   await launch("tel:"+orderList[i]['address']['adPhone']);
  //                                 },)
  //                               ],
  //                             ),
  //                             SizedBox(height: 10 ,),
  //                             Row(children: [Expanded(child: Text(orderList[i]['address']['addressDetail']))],),
  //                             Divider(),
  //                             Row(
  //                               mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //                               children: [
  //                                 Text("正在备餐"),
  //                                 GestureDetector(child: Container(
  //                                   padding: EdgeInsets.symmetric(vertical: 5,horizontal: 10),child: Text("出餐完成"),decoration: BoxDecoration(border: Border.all(color: Colors.black , width: 0) ,),
  //                                 ),onTap: () async{
  //                                   print("订单"+orderList[i]['id']+"出餐完成"+" 商家ID："+merchantID);
  //                                   var res  =await HttpUtil().get("/waimai/mOder/merchantChucan?merchantId="+merchantID+"&orId="+orderList[i]['id']);
  //                                   if(res['code']==200){
  //                                     Fluttertoast.showToast(
  //                                       msg: "出餐完成",
  //                                     );
  //                                     // 刷新页面
  //                                     MyRoute.replace(Index(showIndex: "0",mType: mType,));
  //                                     // setState(() {
  //                                     //   _getOrder();
  //                                     // });
  //                                   }else{
  //                                     Fluttertoast.showToast(
  //                                       msg: res['msg'],
  //                                     );
  //                                   }
  //                                 },)
  //                               ],
  //                             ),
  //                             SizedBox(height: 10 ,),
  //                             Row(
  //                               mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //                               children: [
  //                                 Row(
  //                                   children: [
  //                                     Text(orderList[i]['rider']['qsName']),
  //                                     Container(padding: EdgeInsets.symmetric(vertical: 2,horizontal:5),child: Text("骑手",style: TextStyle(color: Colors.white),),decoration: BoxDecoration(border: Border.all(color: Colors.black , width: 0) ,color: Colors.blueAccent),)
  //                                   ],
  //                                 ),
  //                                 GestureDetector(child: Icon(Icons.phone),onTap: () async {
  //                                   await launch("tel:"+orderList[i]['rider']['phone']);
  //                                 },)
  //                               ],
  //                             ),
  //                             SizedBox(height: 10 ,),
  //                             Row(
  //                               children: [Text("16:23  骑手已接单")],
  //                             ),
  //                           ],
  //                         ),
  //                         decoration: BoxDecoration(
  //                           // color: Colors.orangeAccent,
  //                           // shape: BoxShape.rectangle,
  //                         ),
  //                       ),
  //                     ),
  //                     ScrollOnExpand(
  //                       scrollOnExpand: true,
  //                       scrollOnCollapse: false,
  //                       child: ExpandablePanel(
  //                         theme: const ExpandableThemeData(
  //                           headerAlignment: ExpandablePanelHeaderAlignment.center,
  //                           tapBodyToCollapse: true,
  //                         ),
  //                         header: Padding(
  //                             padding: EdgeInsets.all(10),
  //                             child: Text(
  //                               "商品("+orderList[i]['morderDetailList'].length.toString()+")",
  //                               style: Theme.of(context).textTheme.body2,
  //                             )
  //                         ),
  //                         expanded: Column(   // 展开的内容
  //                           crossAxisAlignment: CrossAxisAlignment.start,
  //                           children: [
  //                             _getOrderDetail(orderList[i]['morderDetailList'])
  //                           ],
  //                         ),
  //                         builder: (_, collapsed, expanded) {
  //                           return Padding(
  //                             padding: EdgeInsets.only(left: 10, right: 10, bottom: 10),
  //                             child: Expandable(
  //                               collapsed: collapsed,
  //                               expanded: expanded,
  //                               theme: const ExpandableThemeData(crossFadePoint: 0),
  //                             ),
  //                           );
  //                         },
  //                       ),
  //                     ),
  //                   ],
  //                 ),
  //               ),
  //             )
  //         )
  //     );
  //   }
  //   return Container(
  //     child: Column(children: x),
  //   );
  // }

  //得订单详情
  _getOrderDetail(orderDetailList){
    List<Widget> x = [];
    for(int i=0;i<orderDetailList.length;i++){
      x.add(
          Row(
              children: [
                Container(
                  width: ScreenUtil().setWidth(230),
                  height: ScreenUtil().setHeight(45),
                  child: Row(
                    children: [
                      Expanded(child: Text(orderDetailList[i]['mgoods']['gname']),),
                    ],
                  ),
                ),
                // Text(orderDetailList[i]['mgoods']['gname']),
                Text("*"+orderDetailList[i]['odNum'].toString()),
                Text("￥"+orderDetailList[i]['odCost'].toString()),
              ],mainAxisAlignment: MainAxisAlignment.spaceBetween
          )
      );
    }
    return Container(
      child: Column(children: x),
    );
  }
}

class Card1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ExpandableNotifier(
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Card(
            clipBehavior: Clip.antiAlias,
            child: Column(
              children: <Widget>[
                SizedBox(
                  // height: 150,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("张无忌"),
                            GestureDetector(child: Icon(Icons.phone),onTap: () async{
                              launch("tel:"+'110'); // 模拟器直接调用，不要判断.真机还不知道是否可行
                              // if( await canLaunch("tel:"+'110')){
                              // await launch("tel:"+'10');
                              // }else{
                              // throw "拨号失败"; // 模拟器会失败，真机可以拨号
                              // }
                            },)
                          ],
                        ),
                        SizedBox(height: 10 ,),
                        Row(children: [Text("天元区珠江北路幸福大厦")],),
                        Divider(),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("正在备餐"),
                            Container(padding: EdgeInsets.symmetric(vertical: 5,horizontal: 10),child: Text("出餐完成"),decoration: BoxDecoration(border: Border.all(color: Colors.black , width: 0) ,),)
                          ],
                        ),
                        SizedBox(height: 10 ,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text("王重阳"),
                                Container(padding: EdgeInsets.symmetric(vertical: 2,horizontal:5),child: Text("骑手"),decoration: BoxDecoration(border: Border.all(color: Colors.black , width: 0) ,),)
                              ],
                            ),
                            GestureDetector(child: Icon(Icons.phone),onTap: () async{
                              launch("tel:"+'120'); // 模拟器直接调用，不要判断.真机还不知道是否可行
                              // if( await canLaunch("tel:"+'120')){
                              // await launch("tel:"+'120');
                              // }else{
                              // throw "拨号失败"; // 模拟器会失败，真机可以拨号
                              // }
                            },)
                          ],
                        ),
                        SizedBox(height: 10 ,),
                        Row(
                          children: [Text("16:23  骑手已接单")],
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                      // color: Colors.orangeAccent,
                      // shape: BoxShape.rectangle,
                    ),
                  ),
                ),
                ScrollOnExpand(
                  scrollOnExpand: true,
                  scrollOnCollapse: false,
                  child: ExpandablePanel(
                    theme: const ExpandableThemeData(
                      headerAlignment: ExpandablePanelHeaderAlignment.center,
                      tapBodyToCollapse: true,
                    ),
                    header: Padding(
                        padding: EdgeInsets.all(10),
                        child: Text(
                          "商品(3)",
                          style: Theme.of(context).textTheme.body2,
                        )),
                    // collapsed: Text(   // 收起的文字内容
                    //   loremIpsum,
                    //   softWrap: true,
                    //   maxLines: 2,
                    //   overflow: TextOverflow.ellipsis,
                    // ),
                    expanded: Column(   // 展开的内容
                      crossAxisAlignment: CrossAxisAlignment.start,
                      // children: <Widget>[
                      //   for (var _ in Iterable.generate(5))
                      //     Padding(
                      //         padding: EdgeInsets.only(bottom: 10),
                      //         child: Text(
                      //           loremIpsum,
                      //           softWrap: true,
                      //           overflow: TextOverflow.fade,
                      //         )),
                      // ],
                      children: [
                        Row(children: [Text("辣椒炒肉"),Text("*1"),Text("￥19")],mainAxisAlignment: MainAxisAlignment.spaceBetween,),
                        Row(children: [Text("辣椒炒肉"),Text("*1"),Text("￥19")],mainAxisAlignment: MainAxisAlignment.spaceBetween,),
                        Row(children: [Text("辣椒炒肉"),Text("*1"),Text("￥19")],mainAxisAlignment: MainAxisAlignment.spaceBetween,),
                        Row(children: [Text("小计"),Text("￥22")],mainAxisAlignment: MainAxisAlignment.spaceBetween,),
                      ],
                    ),
                    builder: (_, collapsed, expanded) {
                      return Padding(
                        padding: EdgeInsets.only(left: 10, right: 10, bottom: 10),
                        child: Expandable(
                          collapsed: collapsed,
                          expanded: expanded,
                          theme: const ExpandableThemeData(crossFadePoint: 0),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        )
    );
  }
}